import { Module } from 'vuex'
import { getResource } from '@/api/resource'

export interface TerminalState2 {
  data: kv[],
  region: kv[]
}

interface kv {
  label: string;
  value: string;
}


const regionList = (data: any) => {
  if (Array.isArray(data)) {
    const datas: kv[] = []
    const region: kv[] = []
    data.forEach((v: any) => {
      datas.push(v)
      v.children.forEach((ele: any) => {
        region.push(ele)
      })
    })
    return { datas , region }
  } else {
    return { datas:[],regions: [] }
  }
}

// eslint-disable-next-line
const terminal2: Module<TerminalState2, any> = {
  namespaced: true,
  state: () => ({
    data: [],
    region: []
  }),
  getters: {
    getRegionByValue (state) {
      return (key: string) => state.region.find(item => item.value === key)?.label
    }
  },
  mutations: {
    SET_TERMINAL (state, payload) {
      state.data = payload
    },
    SET_REGION (state, payload) {
      state.region = payload
    }
  },
  actions: {
    getTerminal2 ({ commit }) {
      return new Promise((resolve, reject) => {
        getResource('inout_terminal').then(res => {
          if (res && res.data?.properties?.meta) {
            const { datas, region } = regionList(res.data?.properties?.meta)
            commit('SET_TERMINAL', datas)
            //const { regions } = regionList(res.data?.properties?.meta)
            commit('SET_REGION', region)
            resolve(res)
          } else {
            reject(res)
          }
        }).catch(reject)
      })
    }

  }
}

export default terminal2
